package transport

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sync"
	"unicode/utf8"
)

// StdioTransport stdio传输层
type StdioTransport struct {
	reader *bufio.Reader
	writer *bufio.Writer
	mu     sync.Mutex
	closed bool
}

// NewStdioTransport 创建新的stdio传输层
func NewStdioTransport() *StdioTransport {
	return &StdioTransport{
		reader: bufio.NewReader(os.Stdin),
		writer: bufio.NewWriter(os.Stdout),
	}
}

// ReadMessage 读取一条消息（以换行符分隔）
func (t *StdioTransport) ReadMessage() ([]byte, error) {
	if t.closed {
		return nil, fmt.Errorf("transport is closed")
	}

	line, err := t.reader.ReadBytes('\n')
	if err != nil {
		if err == io.EOF {
			return nil, io.EOF
		}
		return nil, fmt.Errorf("failed to read message: %w", err)
	}

	// 验证UTF-8编码
	if !utf8.Valid(line) {
		return nil, fmt.Errorf("invalid UTF-8 encoding")
	}

	// 移除换行符
	if len(line) > 0 && line[len(line)-1] == '\n' {
		line = line[:len(line)-1]
	}
	if len(line) > 0 && line[len(line)-1] == '\r' {
		line = line[:len(line)-1]
	}

	return line, nil
}

// WriteMessage 写入一条消息（添加换行符）
func (t *StdioTransport) WriteMessage(msg []byte) error {
	t.mu.Lock()
	defer t.mu.Unlock()

	if t.closed {
		return fmt.Errorf("transport is closed")
	}

	// 验证UTF-8编码
	if !utf8.Valid(msg) {
		return fmt.Errorf("invalid UTF-8 encoding")
	}

	// 写入消息
	if _, err := t.writer.Write(msg); err != nil {
		return fmt.Errorf("failed to write message: %w", err)
	}

	// 添加换行符
	if err := t.writer.WriteByte('\n'); err != nil {
		return fmt.Errorf("failed to write newline: %w", err)
	}

	// 刷新缓冲区
	if err := t.writer.Flush(); err != nil {
		return fmt.Errorf("failed to flush: %w", err)
	}

	return nil
}

// Close 关闭传输层
func (t *StdioTransport) Close() error {
	t.mu.Lock()
	defer t.mu.Unlock()

	if t.closed {
		return nil
	}

	t.closed = true
	return t.writer.Flush()
}
